from django.contrib import admin
from .models import HistoryQA, ProjectInfo, PartitionInfo
from django.utils.translation import gettext_lazy
from user.models import UserProfile
from history_qa.views import vector_db, embedding_name2dim_dict
from collections import defaultdict


# class EmbeddingTypeAdmin(admin.ModelAdmin):
#     list_display = ('name', 'description', 'dim', 'status', 'create_time', 'update_time')
#     readonly_fields = ('name', 'dim', 'status', 'create_time', 'update_time')
#
#     list_filter = ['name']
#     list_per_page = 10
#     SIMPLEUI_LOGO = "fa fa-envelope-open"
#
#     def has_add_permission(self, request=None):
#         # Disable add
#         return False
#     def has_delete_permission(self, request=None, obj=None):
#         # Disable delete
#         return False
#
#     fieldsets = (
#         (gettext_lazy('嵌入向量模型'), {'fields': ('name', 'description', 'dim')}),
#     )

    
class HistoryQAAdmin(admin.ModelAdmin):
    list_display = ('id', 'user_id', 'question', 'answer', 'feedback', 'embedding_type', 'session_id', 'project_name', 'partition_name', 'comment', 'status', 'create_time')
    list_filter = ['partition_name__name', 'session_id', 'source', 'feedback']
    search_fields = ['question']
    readonly_fields = ('id', 'code', 'user_id', 'create_time')
    list_per_page = 10
    SIMPLEUI_LOGO = "fa fa-envelope"
    
    def has_delete_permission(self, request=None, obj=None):
        # Disable delete
        return False
    
    def get_queryset(self, request):
        qs = super(HistoryQAAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs.filter(status=1)
        historyqa_permission = UserProfile.objects.get(username=request.user.username).historyqa_permission.all()
        return qs.filter(project_name__in=historyqa_permission, status=1)
    
    actions = ['really_delete_selected']
    
    def delete_model(self, request, obj):
        project_name = obj.project_name
        uid = obj.code
        qs = HistoryQA.objects.filter(code=uid, project_name=project_name)
        self.really_delete_selected(request, qs)

    def really_delete_selected(self, request, queryset):
        project_del_idx_dict = defaultdict(dict)
        
        # mysql数据库删除
        for obj in queryset:
            project_name = obj.project_name.name
            uid = obj.code
            embedding_type = obj.embedding_type.name
            embedding_dim = embedding_name2dim_dict[embedding_type]
            if embedding_dim in project_del_idx_dict[project_name]:
                project_del_idx_dict[project_name][embedding_dim].append(uid)
            else:
                project_del_idx_dict[project_name][embedding_dim] = [uid]
            
        # milvus删除
        for project_name, del_idx_dict in project_del_idx_dict.items():
            return_status = vector_db.delete_data(del_idx_dict, project_name)
            if not return_status:
                break
        if return_status:
            for obj in queryset:
                obj.delete()

            if queryset.count() == 1:
                message_bit = "1 条记录被"
            else:
                message_bit = "%s 条记录被" % queryset.count()
            self.message_user(request, "%s成功删除." % message_bit)

    really_delete_selected.short_description = "－删除"

    
    fieldsets = ( 
        (gettext_lazy('历史对话内容'), {'fields': ('question', 'answer', 'feedback')}),
        (gettext_lazy('历史对话其他信息'), {'fields': ('source', 'embedding_type', 'user', 'user_id', 'session_id')}),
        (gettext_lazy('所属项目'), {'fields': ('project_name', 'partition_name')}),
    )


class ProjectInfoAdmin(admin.ModelAdmin):
    list_display = ('name', 'description', 'status', 'create_time', 'update_time')
    readonly_fields = ('name', 'real_name', 'status', 'create_time', 'update_time')
    list_filter = ['name']
    list_per_page = 10
    SIMPLEUI_LOGO = "fa fa-envelope-open"
    
    def has_add_permission(self, request=None):
        # Disable add
        return False
    def has_delete_permission(self, request=None, obj=None):
        # Disable delete
        return False
    def get_queryset(self, request):
        qs = super(ProjectInfoAdmin, self).get_queryset(request)
        # if request.user.is_superuser:
        #     return qs
        return qs.filter(status=1)

    fieldsets = ( 
        (gettext_lazy('项目信息'), {'fields': ('name', 'description')}),
    )

    
class PartitionInfoAdmin(admin.ModelAdmin):
    list_display = ('name', 'description', 'project_name', 'status', 'create_time', 'update_time')
    list_filter = ['name', 'project_name', 'status']
    readonly_fields = ('name', 'project_name', 'status', 'create_time', 'update_time')
    list_per_page = 10
    SIMPLEUI_LOGO = "fa fa-envelope-open"

    def has_add_permission(self, request=None):
        # Disable add
        return False
    def has_delete_permission(self, request=None, obj=None):
        # Disable delete
        return False
    def get_queryset(self, request):
        qs = super(PartitionInfoAdmin, self).get_queryset(request)
        # if request.user.is_superuser:
        #     return qs
        return qs.filter(status=1)
    
    fieldsets = ( 
        (gettext_lazy('历史对话库信息'), {'fields': ('name', 'description', 'project_name')}), # 添加模型里的字段openid
 
        # (gettext_lazy('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )



admin.site.register(HistoryQA, HistoryQAAdmin)
admin.site.register(ProjectInfo, ProjectInfoAdmin)
admin.site.register(PartitionInfo, PartitionInfoAdmin)
# admin.site.register(EmbeddingType, EmbeddingTypeAdmin)
